// void, Obj This 

Building bld;
Settlement this;
Query qMil, qMilNoSentry;
ObjList l;
Unit u;
Item item;
int i;

//pr("modernize dziala");
bld = This.AsBuilding();
this = bld.settlement;

if (bld.IsValid) 
{
	qMil = Intersect(ObjsInCircle(bld.pos, 900, "Military"), ClassPlayerObjs("Military", .player));
	qMilNoSentry = Subtract(qMil, ClassPlayerObjs("Sentry", .player)); 
	l = qMilNoSentry.GetObjList();
	for (i = l.count; i > 0;) 
	{
		i -= 1;
		u = l[i].AsUnit();
        if(u.IsValid){
			if (!bld.IsEnemy(u)){
				if(EnvReadInt(.player, "resources/Iron") > 0){ 
	                if(!u.HasItem("Steel weapon and armor")){
						if(u.maxhealth > 400){
							u.AddItem("Steel weapon and armor"); 
	                        EnvWriteInt(.player, "resources/Iron", EnvReadInt(.player, "resources/Iron") - 1);
                        }
	                }
	            }
                if(EnvReadString(bld.player, "Generals School") == "researched"){
					//pr("generals modernize");
                    if(u.AsHero.IsValid){
						if(u.HasItem("Officer") && !u.HasItem("General") && !u.HasItem("Leader")){
							//pr("generals modernize");
							item = u.GetItem(2);
                            if(item.IsValid)
								u.ExchangeItem(item, "General");
                        }
                    }
                }  
                                
				if (EnvReadInt(this, "items/Bear teeth amulet") == 1){
					if(!u.HasItem("Bear teeth amulet")){
						u.AddItem("Bear teeth amulet");
					}
				}
				if (EnvReadInt(this, "items/Herb amulet of luck") == 1){
					if(!u.HasItem("Herb amulet of luck")){
						u.AddItem("Herb amulet of luck");
					}
				}
				if (EnvReadInt(this, "items/Belt of might") == 1){
					if(!u.HasItem("Belt of might")){
						u.AddItem("Belt of might");
					}
				}
				if (EnvReadInt(this, "items/God's Gift") == 1){
					if(!u.HasItem("God's Gift")){
						u.AddItem("God's Gift");
					}
				}
				if (EnvReadInt(this, "items/Veteran Guild") == 1){
					if(!u.HasItem("Veteran Guild")){
						u.AddItem("Veteran Guild");
					}                         
				}        
			}
		}
	}

	if(EnvReadInt(.player, "resources/Iron") > 0){ 
		for (i = l.count; i > 0;) 
		{
			i -= 1;
			u = l[i].AsUnit();
			if(u.IsValid){
				if (!bld.IsEnemy(u)){
					if(EnvReadInt(.player, "resources/Iron") > 0){        
						if(!u.HasItem("Steel weapon and armor")){
							u.AddItem("Steel weapon and armor");  
							EnvWriteInt(.player, "resources/Iron", EnvReadInt(.player, "resources/Iron") - 1);
						}
					}
				}
			}
		}
	}
	bld.PlaySound("data/Sound Entities/TownhallModernize.xml");
}